<template>
  <div>
    <el-card class="box-card">
      <h2>用户列表</h2>
      <el-input
          v-model="searchName"
          placeholder="请输入用户名"
          style="margin-bottom: 20px;"
      ></el-input>
      <el-button type="primary" @click="searchUser">查询</el-button>
      <el-table :data="users" style="width: 100%; margin-top: 20px;">
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column label="邮箱">
          <template v-slot="scope">
            <span>{{ scope.row.email || 'null' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="text" @click="editUser(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="users.length === 0" style="text-align: center; margin-top: 20px;">
        没有找到匹配的用户
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      searchName: '',
      users: []
    };
  },
  mounted() {
    this.fetchUsers();
  },
  methods: {
    fetchUsers() {
      this.axios.get('/api/user/get')
          .then(response => {
            const result = response.data;
            if (Array.isArray(result.data)) {
              this.users = result.data;
              console.log(this.users); // 打印用户数据，确保包含 email 字段
            } else {
              console.error('Error: Expected an array but got:', result.data);
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    searchUser() {
      this.axios.get(`/api/user/search`, {params: {username: this.searchName}})
          .then(response => {
            const result = response.data;
            if (Array.isArray(result.data)) {
              this.users = result.data;
            } else {
              this.users = [];
              console.error('Error: Expected an array but got:', result.data);
            }
          })
          .catch(error => {
            this.users = [];
            console.error('Error searching users:', error);
          });
    },
    editUser(user) {
      this.$router.push(`/edit_user2/${user.username}`);
    },
    deleteUser(user) {
      this.axios.delete(`/api/user/delete/${user.username}`)  // 修改为根据用户名删除
          .then(() => {
            this.fetchUsers();
          })
          .catch(error => {
            console.error('Error deleting user:', error);
          });
    }
  }
}
</script>
`/api/user/delete/${selectedUsername}`

<style scoped>
.box-card {
  margin: auto;
  width: 800px;
}
</style>
